package testa;

import entity.Jd;
import entity.Qx;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Iterator;

public class test {
    Session session=null;
    Transaction transaction=null;
    @Before
    public  void init(){
        Configuration confi = new Configuration().configure();
        SessionFactory  sessionFactory = confi.buildSessionFactory();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    }
    @Test
    public void test1(){
       Qx qx = (Qx) session.get(Qx.class,1);
        System.out.println(qx.getQxname());

    }
    @Test
    public void oneToMany(){ //一对多进行查询
        Qx qx = (Qx) session.get(Qx.class,1);
        Iterator<Jd> jds  = qx.getJds().iterator();
        while (jds.hasNext()){
            System.out.println(jds.next().getJdname());
        }
    }
    @Test
    public void manyToOne(){ //多对一进行查询

        Jd jd1 = (Jd) session.get(Jd.class,4);
        System.out.println(jd1.getQx().getQxname());
    }
    @Test
    public void addManytoOne(){ //对多对一一的一方进行插入数据
        Qx qx = new Qx("项城");
        session.saveOrUpdate(qx);
    }
     @Test
    public  void addManytoOne2(){//对多对一一的多的一方进行插入数据
        Qx qx = new Qx();
        qx.setQxid(2);
        Jd jd = new Jd("张若均",qx);
        session.saveOrUpdate(jd);
    }
    @Test
    public  void addManytoOne3(){//一次插入数据到多的一方 这个出现了问题
        Qx qx = new Qx();
        qx.setQxid(3);
        Jd jd1 = new Jd("黄晓明",qx);
        Jd jd2 = new Jd("赵薇",qx);
        session.save(jd1);
        session.save(jd2);


//       qx.setQxname("上海");
//        System.out.println(qx.getJds());
//       qx.getJds().add(jd1);
//       qx.getJds().add(jd2);
//       session.save(qx);
    }

    @Test
    public void deleteMany(){ //也就是说删除街道的一方
        Jd jd = (Jd) session.get(Jd.class,5);
       // boolean b = jd.getQx().getJds().remove(jd);
        session.delete(jd);
    }
    @Test
    public  void deleteOne(){ //也就是说删除城区的一方
        Qx qx = (Qx) session.get(Qx.class,2);
        session.delete(qx);
    }

    @After
    public void des(){
        transaction.commit();
        session.close();

    }


}
